<template>
  <div class="great-collapse" :class="{active: !hide}" @mouseup="handleMouseEvent" @mousemove="handleMouseEvent">
    <div class="head" @click="handleClick">
      <div class="point"></div>
      <div class="title">{{title}}</div>
      <div class="collapse" :class="`${hide ? 'hide' : ''}`">▽</div>
    </div>
    <div class="body">
      <slot>
        内容
      </slot>
    </div>
  </div>
</template>

<script>
export default {
  name: 'GreatCollapse',
  data() {
    return {
      hide: false,
      oldHTML: '',
    };
  },

  props: {
    title: {
      type: String,
      default: '标题'
    }
  },

  mounted() {

  },

  methods: {
    handleClick() {
      this.hide = !this.hide
      this.handleMouseEvent()
    },
    handleMouseEvent() {
      // 如果innerHTML发生变化，则触发重新计算高度
      if (this.oldHTML != this.$el.parentElement.innerHTML) {
        // 第一次点击，存储innerHTML
        if (!this.oldHTML) {
          this.oldHTML = this.$el.parentElement.innerHTML
        }
        let oldHeight
        if (this.$el.style.height) {
          // 不为auto时
          oldHeight = this.$el.style.height
        } else {
          // 为auto时
          oldHeight = getComputedStyle(this.$el).height
        }
        // 第一次，获取元素真实高度
        this.$el.style.height = 'fit-content'
        let height
        if (this.hide) {
          height = getComputedStyle(this.$el.querySelector('.head')).height
        } else {
          height = getComputedStyle(this.$el).height
        }
        // 第二次，赋予元素初始高度
        this.$el.style.height = oldHeight
        // 读取元素几何数据，触发重绘
        this.$el.offsetHeight
        // 第三次，赋予元素最终高度
        this.$el.style.height = height
      }
    },
  },
};
</script>

<style lang="less" scoped>
.great-collapse {
  height: 58px;
  width: 100%;
  transition: height 0.5s;
  overflow: hidden;
  &.active {
    height: auto;
    & > .head > .point {
      background: #4af905;
    }
    & > .head > .collapse {
      transform: rotate(180deg);
    }
  }
  .head {
    width: 100%;
    height: 58px;
    line-height: 58px;
    background: #fff;
    box-shadow: 0px 2px 4px 0px #DEE7ED;
    border-radius: 4px;
    position: relative;
    cursor: pointer;
    .point {
      position: absolute;
      left: 17px;
      top: 25px;
      display: inline-block;
      width: 8px;
      height: 8px;
      background: #999999;
      border-radius: 50%;
    }
    .title {
      position: absolute;
      left: 36px;
      top: 0;
      display: inline-block;
      height: 58px;
      line-height: 58px;
      width: auto;
    }
    .collapse {
      position: absolute;
      right: 17px;
      display: inline-block;
    }
  }
  .body {
    width: 100%;
    height: auto;
    background: transparent;
    padding: 19px 0;
    box-sizing: border-box;
    position: relative;
  }
}
</style>